package com.king.springcloud.service.impl;

import com.king.springcloud.dao.OrderDao;
import com.king.springcloud.domain.Order;
import com.king.springcloud.service.AccountService;
import com.king.springcloud.service.OrderService;
import com.king.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author king
 * @date 2020/10/20 19:41
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private AccountService accountService;
    @Resource
    private StorageService storageService;

    /**
     * 创建订单 -> 调用库存服务扣减库存 -> 调用账户服务扣减余额 -> 修改订单状态
     * @param order
     */
    @Override
    @GlobalTransactional(name = "order-seata", rollbackFor = Exception.class) // 分布式全局异常捕获回滚
    public void create(Order order) {
        log.info("开始创建订单~~~~~~~~~~~~~~");
        orderDao.create(order);

        log.info("订单微服务开始调用库存做扣减~~~~~~~~~~");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("订单微服务结束调用~~~~~~~~~~");

        log.info("账户微服务开始调用账户做扣减~~~~~~~~~~");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("账户微服务结束调用~~~~~~~~~~");


        log.info("修改订单状态开始~~~~~~~~~~~~~~");
        orderDao.update(order.getUserId(), 0);
        log.info("修改订单状态结束~~~~~~~~~~~~~~");
    }
}
